import binary, random
from tori.akatsak import akatsa
# -rodata
# -data
# -bss
# -text

def plain_bin(o,out, gui=False):
    out.write("%PBIN") #Magic number
    out.write(binary.bitar_hutsa(len(o.rodata), gui=gui))
    out.write(binary.bitar_hutsa(len(o.data), gui=gui))
    out.write(binary.bitar_hutsa(o.bss, gui=gui))
    out.write(binary.bitar_hutsa(len(o.text)*2, gui=gui))
    # kateak
    for i in o.rodata:
        out.write(binary.bitar_hutsa(i, gui=gui))
    # asignatutako datuak
    for i in o.data:
        out.write(binary.biren_osagarria(i, gui=gui))
    # ez-hasieratutako datuak ez dira kanporatu behar, noski
    # aginduak
    for i in range(len(o.text)):
        out.write(binary.agindua_bitarrera(o.txukundu(o.text[i],i), gui=gui))
    return False


def read_plain_bin(dock):
    rodata = binary.i_bitar_hutsa(dock.read(2))
    data   = binary.i_bitar_hutsa(dock.read(2))
    bss    = binary.i_bitar_hutsa(dock.read(2))
    text   = binary.i_bitar_hutsa(dock.read(2))
    datuak = []
    for i in range(rodata):
        datuak.append(binary.i_bitar_hutsa(dock.read(2)))
    for i in range(data):
        datuak.append(binary.i_biren_osagarria(dock.read(2)))
    for i in range(bss):
        datuak.append(random.randint(-2**16,2**16-1))
    aginduak = []
    for i in range(text):
        aginduak.append(binary.i_bitar_hutsa(dock.read(2)))

    return rodata, data, bss, text, datuak, aginduak        


def text_bin(o,out,gui=False):
    "plain_bin baina irteera ascii motako 0 eta 1-ak"
    out.write("%TBIN") #Magic number
    out.write(binary.a_bitar_hutsa(len(o.rodata), gui=gui))
    out.write(binary.a_bitar_hutsa(len(o.data), gui=gui))
    out.write(binary.a_bitar_hutsa(o.bss, gui=gui))
    out.write(binary.a_bitar_hutsa(len(o.text)*2, gui=gui))
    # kateak
    for i in o.rodata:
        out.write(binary.a_bitar_hutsa(i, gui=gui))
    # asignatutako datuak
    for i in o.data:
        out.write(binary.biren_osagarria(i, gui=gui))
    # ez-hasieratutako datuak ez dira kanporatu behar, noski
    # aginduak
    for i in range(len(o.text)):
        out.write(binary.a_agindua_bitarrera(o.txukundu(o.text[i],i), gui=gui))
    return False


